python tkiner 点击多个按钮开启多线程并打开多个窗口,点击打开的窗口关闭按钮实现线程关闭,并关闭此窗口

您所在的位置:网站首页 idea 开启多线程 python tkiner 点击多个按钮开启多线程并打开多个窗口,点击打开的窗口关闭按钮实现线程关闭,并关闭此窗口

python tkiner 点击多个按钮开启多线程并打开多个窗口,点击打开的窗口关闭按钮实现线程关闭,并关闭此窗口

2023-04-02 02:40| 来源: 网络整理| 查看: 265

import threading import tkinter as tk class MyThread(threading.Thread): def __init__(self, window): super().__init__() self.window = window self.stop_event = threading.Event() def run(self): while not self.stop_event.is_set(): # do something pass def stop(self): self.stop_event.set() self.window.destroy() # Close the window when stopping thread. def create_window(thread): """Create a new window and register the thread's stop method.""" window = tk.Toplevel() window.protocol("WM_DELETE_WINDOW", thread.stop) thread.window = window def start_thread(): """Create a new thread and window.""" thread = MyThread(None) thread.start() create_window(thread) root = tk.Tk() start_button1 = tk.Button(root, text="Start 1", command=start_thread) start_button1.pack() start_button2 = tk.Button(root, text="Start 2", command=start_thread) start_button2.pack() root.mainloop()

在上面的代码中,我们修改了MyThread类的stop()方法,以便它能够停止相应的线程并关闭窗口。具体地说,当线程停止后,该方法将调用窗口的destroy()方法来关闭窗口本身。这样,当用户单击窗口关闭按钮时,窗口将被销毁,相应的线程将被停止,而不仅仅是停止线程。

请注意,您可能需要根据您的应用程序的要求进行修改和扩展上面的代码。例如,在stop()方法中,您可以添加其他清理代码,例如关闭数据库连接或保存文件等。同样,您可以为每个按钮添加自定义参数来启动不同的线程或执行不同的操作。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3